<template>
  <div id="all">
    <userItem></userItem>
    <asideRouteTeacher current-page="2-1"></asideRouteTeacher>
    <div id="main">
        <el-table
            :data="tableData.filter(data => !search || data.name.toLowerCase().includes(search.toLowerCase())|| data.limitdate.toLowerCase().includes(search.toLowerCase()))"
            style="width: 100%" stripe border max-height="400" size="big" fit empty-text="暂无数据">
          <el-table-column
              label="课程名称"
              prop="name" sortable="true">
          </el-table-column>
          <el-table-column
            label="截止日期"
            prop="limitdate" sortable="true" sort-by="date">
        </el-table-column>
          <el-table-column
              label="当前人数"
              prop="number" sortable="true" sort-by="number">
          </el-table-column>
          <el-table-column
              align="right">
            <template slot="header" slot-scope="scope">
              <el-input
                  v-model="search"
                  size="mini"
                  placeholder="搜索名称/日期"/>
            </template>
            <template slot-scope="scope">
              <el-button
                  size="mini"
                  @click="handleDetail(scope.$index, scope.row)" type="warning" plain>信息</el-button>
              <el-button
                size="mini"
                @click="handleEdit(scope.$index, scope.row)" icon="el-icon-edit" circle plain></el-button>
              <el-button
                  size="mini"
                  type="danger"
                  @click="handleDelete(scope.$index, scope.row)" icon="el-icon-delete" circle></el-button>
            </template>
          </el-table-column>
        </el-table>
      <el-button v-on:click="add" id="addbut">添加新课程</el-button>

    </div>

    <div>
      <el-dialog
          title="详细信息"
          :visible.sync="dialogVisible"
          width="30%"
          :before-close="handleClose">
        <span>{{intro}}</span>
        <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
  </span>
      </el-dialog>
    </div>

    <!-- 这个是修改课程信息时会弹出的对话框-->
    <div>
      <el-dialog title="修改课程信息" :visible.sync="editVisible" width="450px" >
      <el-form :model="form" :rules="rules" :label-position="top" ref="form" class="demo-ruleForm">
        <el-form-item label="课程名称" :label-width="formLabelWidth" prop="name">
          <el-input v-model="form.name" autocomplete="off" ></el-input>
        </el-form-item>
        <el-form-item label="截止日期" :label-width="formLabelWidth" prop="limitdate">
          <!-- 直接使用日期选择框，不给错误输入留下机会-->
          <div class="block">
            <el-date-picker
                v-model="form.limitdate"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd">
            </el-date-picker>
          </div>
        </el-form-item>
        <el-form-item label="详细信息" :label-width="formLabelWidth" prop="intro">
          <el-input v-model="form.intro" autocomplete="off" type="textarea" ></el-input>
        </el-form-item>
        <el-form-item label="学分" :label-width="formLabelWidth" prop="score">
          <el-input v-model="form.score" autocomplete="off" type="textarea" ></el-input>
        </el-form-item>
        <el-form-item label="上课时间" :label-width="formLabelWidth" prop="time">
          <el-input v-model="form.time" autocomplete="off" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="rset">取 消</el-button>
        <el-button type="primary" @click="upload('form')" >确 定</el-button>
      </div>
    </el-dialog></div>

    <!-- 这个是添加新课程时会弹出的对话框-->
    <div><el-dialog title="创建新课程" :visible.sync="addVisible" width="450px" >
      <el-form :model="addform" :rules="rules" :label-position="top" ref="addform" class="demo-ruleForm">
        <el-form-item label="课程名称" :label-width="formLabelWidth" prop="name">
          <el-input v-model="addform.name" autocomplete="off" ></el-input>
        </el-form-item>
        <el-form-item label="截止日期" :label-width="formLabelWidth" prop="limitdate">
          <!-- 直接使用日期选择框，不给错误输入留下机会-->
          <div class="block">
            <el-date-picker
                v-model="addform.limitdate"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
            >
            </el-date-picker>
          </div>
        </el-form-item>
        <el-form-item label="详细信息" :label-width="formLabelWidth" prop="intro">
          <el-input v-model="addform.intro" autocomplete="off" type="textarea"></el-input>
        </el-form-item>
        <el-form-item label="学分" :label-width="formLabelWidth" prop="score">
        <el-input v-model="addform.score" autocomplete="off" type="textarea"></el-input>
      </el-form-item>
        <el-form-item label="上课时间" :label-width="formLabelWidth" prop="time">
          <el-input v-model="addform.time" autocomplete="off" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit('addform')" >确 定</el-button>
      </div>
    </el-dialog></div>
  </div>


</template>

<script>
import userItem from "../components/userItem";
import asideRouteTeacher from "../components/asideRouteTeacher";
import request from "../../utils/request";

export default {
  name: "teacherClass",
  components:{
    userItem,
    asideRouteTeacher,
  },
  data() {
     let user=JSON.parse(sessionStorage.getItem("user"))
     request.post("api/course/getCourse",user).then(res=>{
      console.log(user)
      console.log(res.data);
      this.tableData=res.data;
      sessionStorage.setItem("previousData",res.data);
    })
    return {
      editVisible:false,
      addVisible:false,
      dialogVisible: false,
      printuser:user,
      tableData:[],
      timeTableData:[],
      search: '',
      intro:'',

      formLabelWidth: '80px',
      form:{
        name:'',
        limitdate:'',
        intro:'',
        id:'',
        teacher:'',
        time:'',
        score:'',
      },
      addform:{
        name:'',
        limitdate:'',
        intro:'',
        id:'',
        time:'',
        teacher:JSON.parse(sessionStorage.getItem("user")).name,
        score:'',
      },
      rules: {
        name: [
          { required: true, message: '请输入课程名称', trigger: 'blur' },
        ],
        limitdate:[
          {required:true,message:'请填写截止日期',trigger:'blur'}
        ],
        intro:[
          { required:true,message:'请输入您的课程简介',trigger:'blur'},
        ],
        time:[
          {required:true,message:'请输入您的课程时间',trigger:'blur'},
        ],
        score:[
          {required:'number',message:'请输入您的课程学分',trigger:'blur'},
        {required:true,message:'请输入您的课程时间',trigger:'blur'},

        ],
      }
    }
  },
  methods: {
    handleEdit(index, row) {
      console.log(index, row);
      this.form=this.tableData.filter(data => !this.search || data.name.toLowerCase().includes(this.search.toLowerCase())|| data.limitdate.toLowerCase().includes(this.search.toLowerCase()))[index]
      this.editVisible=true;
    },
    handleDetail(index, row) {
      console.log(index, row);
      this.intro=this.tableData.filter(data => !this.search || data.name.toLowerCase().includes(this.search.toLowerCase())|| data.limitdate.toLowerCase().includes(this.search.toLowerCase()))[index].intro;
      this.dialogVisible=true;
    },
    handleDelete(index, row) {
      console.log(index, row);
      request.post("api/course/deleteCourse",this.tableData.filter(data => !this.search || data.name.toLowerCase().includes(this.search.toLowerCase())|| data.limitdate.toLowerCase().includes(this.search.toLowerCase()))[index]).then( res=>{
        this.$message({
        message: '删除成功',
        type: 'warning'
      });
        let user=JSON.parse(sessionStorage.getItem("user"))
        request.post("api/course/getCourse",user).then(res=>{this.tableData=res.data;})
      })
  },
    handleClose(done) {
      this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
    },
    upload(formName) {
      this.$refs[formName].validate((valid) => { if (valid) {
        request.put("api/course/upload",this.form).then(res=>{
          console.log(res.msg)
          if(res.code==="-1"){
            this.$message({
              message: '上课时间设置错误！（请以"1-3,2,4"类似的格式）',
              type: 'error'
            });
          }else{
            this.$message({
              message: '修改成功',
              type: 'success'
            });
            this.editVisible=false;
          }
        })

      }})
    },

    add(){
      this.addVisible=true
    },
    submit(formName) {
      this.$refs[formName].validate((valid) => { if (valid) {
        request.post("api/course/add",this.addform).then(res=> {
          console.log(res.msg)
          if (res.code === "0") {
            this.$message({
              message: '添加成功！',
              type: 'success'
            });
            this.addVisible=false
            let user=JSON.parse(sessionStorage.getItem("user"))
            request.post("/api/course/getCourse",user).then(res=>{
              this.tableData=res.data;
            })
          } else{
            if(res.code==="-2"){
              this.$message({
                message: '上课时间设置错误！（请以"1-3,2,4"类似的格式）',
                type: 'error'
              });
            }else{
              this.$message({
                message: '该课程已存在！',
                type: 'error'
              });
            }
          }
        })

      }})
    },
    rset(){
      this.editVisible=false;
      let user=JSON.parse(sessionStorage.getItem("user"))
      request.post("/api/course/getCourse",user).then(res=>{
        this.tableData=res.data;
      })
    }
  },
}
</script>

<style scoped>
#main{
  position:absolute;
  right: 23%;
  width: 50%;
  margin-top: 50px;
}
#addbut{
  position: absolute;
  right: 0;
  margin-top: 40px;
}
</style>
